﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;

namespace TireService.Web.UserControls
{
    public partial class ucEditTireSet : System.Web.UI.UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void callbackEditTireSetPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int TireSetId)
        {
            // Show usercontrol edit form
            pEditTireSet.Visible = true;

            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            // Load form data
            LoadUserControlData(db);
            

            if (TireSetId != 0)
            {
                LoadTireSet(TireSetId, db);
            }
            else
            {
                // Error
                throw new ArgumentException("Hjulsæt ikke fundet");
            }
        }

        /// <summary>
        /// Function that load form data for tireset edit
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void LoadUserControlData(TireServiceDB db)
        {
            ddlTireSpeedIndex.DataSource = db.GetTireSpeedIndex();
            ddlTireSpeedIndex.TextField = "Description";
            ddlTireSpeedIndex.ValueField = "TireSpeedIndexId";
            ddlTireSpeedIndex.DataBind();

            ddlTireLoadIndex.DataSource = db.GetTireLoadIndex();
            ddlTireLoadIndex.TextField = "Description";
            ddlTireLoadIndex.ValueField = "TireLoadIndexId";
            ddlTireLoadIndex.DataBind();

            ddlTireBrand.DataSource = db.GetTireBrands();
            ddlTireBrand.TextField = "Description";
            ddlTireBrand.ValueField = "TireBrandId";
            ddlTireBrand.DataBind();
        }

        /// <summary>
        /// Function that load tireset and set edit form values
        /// </summary>
        /// <param name="TireSetId">Id on tireset to loadTireSet</param>
        /// <param name="db">Connection to database</param>
        private void LoadTireSet(int TireSetId, TireServiceDB db)
        {
            // Fetch tiresetId
            TireSet tireset = db.GetTireSet(TireSetId);

            // Set values in edit form
            if (tireset != null)
            {
                rbTireType.Items.FindByValue(tireset.TireTypeId.ToString()).Selected = true;
                if (tireset.RimType != null) rbRimType.Items.FindByValue(tireset.RimType.ToString()).Selected = true;
                cbExtraBolts.Checked = tireset.ExtraBolts;
                cbHubCaps.Checked = tireset.HubCaps;
                cbLockingBolt.Checked = tireset.LockingBolt;
                cbNeedBalancing.Checked = tireset.NeedBalancing;
                cbRimProtection.Checked = tireset.RimProtection;
                cbRunFlatTire.Checked = tireset.RunFlatTire;
                if (tireset.LastBalancingDate != null) txtLastBalancingDate.Date = Convert.ToDateTime(tireset.LastBalancingDate);
                if (tireset.ManufactureDate != null) txtManufactureDate.Date = Convert.ToDateTime(tireset.ManufactureDate);
                txtTireBrandNote.Text = tireset.TireBrandNote;
                if (tireset.Height != null) ddlHeight.Items.FindByValue(tireset.Height.ToString()).Selected = true;
                if (tireset.Width != null) ddlWidth.Items.FindByValue(tireset.Width.ToString()).Selected = true;
                if (tireset.Size != null) ddlSize.Items.FindByValue(tireset.Size.ToString()).Selected = true;
                if (tireset.SocketWrenchSize != null) ddlSocketWrenchSize.Items.FindByValue(tireset.SocketWrenchSize.ToString()).Selected = true;
                if (tireset.TireBrandId != null) ddlTireBrand.Items.FindByValue(tireset.TireBrandId.ToString()).Selected = true;
                if (tireset.TireLoadIndexId != null) ddlTireLoadIndex.Items.FindByValue(tireset.TireLoadIndexId.ToString()).Selected = true;
                if (tireset.TireSpeedIndexId != null) ddlTireSpeedIndex.Items.FindByValue(tireset.TireSpeedIndexId.ToString()).Selected = true;

                // Determin if stock move is possible (not possible if mounted on car)
                cbReportOnStock.Enabled = (tireset.ContainerCargoRoomId != null);
                cbReportOnStock.Checked = (tireset.TireSetStatusId == (int)Shared.TireSetStatus.AwaitsMoveToStock);

                if (tireset.ContainerCargoRoomId != null)
                {
                    ddlCargoRoom.Enabled = true;
                    ddlCargoRoom.TextField = "CargoRoomNumber";
                    ddlCargoRoom.ValueField = "ContainerCargoRoomId";
                    ddlCargoRoom.DataSource = db.GetContainerCargoRooms(db.GetContainerIdForCargoRoom(Convert.ToInt32(tireset.ContainerCargoRoomId)));
                    ddlCargoRoom.DataBind();
                }
                else
                {
                    ddlCargoRoom.Enabled = false;
                }                
            }
            else
            {
                // Error
                throw new ArgumentException("Hjulsæt kunne ikke loades");
            }
        }

        /// <summary>
        /// Callback function that saves tireset
        /// </summary>
        protected void callBackSaveTireSet_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values from client
                // 0: TireType
                // 1: RimType
                // 2: Size
                // 3: Width
                // 4: Height
                // 5: Speedindex
                // 6: Loadindex
                // 7: Tirebrand
                // 8: Brand note / model
                // 9: Lockingbolt
                // 10: Hubcaps
                // 11: Runflat tire
                // 12: Need balancing
                // 13: Extrabolts
                // 14: Rim protection
                // 15: Last balancing date
                // 16: Manufacture date
                // 17: Socket wrench size
                // 18: TireSetId
                // 19: Report on Stock
                // 20: ContainerCargoRoom (optional)
                string[] param = e.Parameter.Split('|');

                int TireSetId = Convert.ToInt32(param[18]);

                // Initiate datalayer
                TireServiceDB db = new TireServiceDB();

                TireSet tireset = new TireSet();

                if (TireSetId == 0)
                {
                    throw new ArgumentException("Hjulsæt ikke valgt - venligst prøv igen");
                }

                if (TireSetId != 0)
                {
                    // Load tireset
                    tireset = db.GetTireSet(TireSetId);
                }
                tireset.TireTypeId = Convert.ToInt32(param[0]);
                tireset.RimType = Convert.ToInt32(param[1]);
                tireset.Size = Convert.ToDecimal(param[2]);
                tireset.Width = Convert.ToDecimal(param[3]);
                tireset.Height = Convert.ToDecimal(param[4]);
                if (param[5] != "0") tireset.TireSpeedIndexId = Convert.ToInt32(param[5]);
                if (param[6] != "0") tireset.TireLoadIndexId = Convert.ToInt32(param[6]);
                if (param[7] != "0") tireset.TireBrandId = Convert.ToInt32(param[7]);
                if (param[8] != "") tireset.TireBrandNote = Convert.ToString(param[8]);
                tireset.LockingBolt = Convert.ToBoolean(param[9]);
                tireset.HubCaps = Convert.ToBoolean(param[10]);
                tireset.RunFlatTire = Convert.ToBoolean(param[11]);
                tireset.NeedBalancing = Convert.ToBoolean(param[12]);
                tireset.ExtraBolts = Convert.ToBoolean(param[13]);
                tireset.RimProtection = Convert.ToBoolean(param[14]);
                if (param[15] != "") tireset.LastBalancingDate = Convert.ToDateTime(param[15]);
                if (param[16] != "") tireset.ManufactureDate = Convert.ToDateTime(param[16]);
                if (param[17] != "null") tireset.SocketWrenchSize = Convert.ToInt32(param[17]);
                tireset.DummyTireSet = false;

                // Report tireset on stock
                if (Convert.ToBoolean(param[19]) & tireset.TireSetStatusId == (int)Shared.TireSetStatus.AwaitsMoveToStock)
                {
                    int NewContainerCargoRoomId = Convert.ToInt32(param[20]);

                    tireset.TireSetStatusId = (int)Shared.TireSetStatus.OnStock;

                    // Create tiresetlog for tireset
                    TireSetLogBLL bll = new TireSetLogBLL();

                    // Check if selected containercargoroom is already used
                    TireSet TireSetOccupying = db.TireSets.SingleOrDefault(p => p.ContainerCargoRoomId == NewContainerCargoRoomId);

                    int containercargoroomid = Convert.ToInt32(tireset.ContainerCargoRoomId);

                    if (TireSetOccupying == null)
                    {
                        // No tireset is occupying the cargoroom already

                        // Update tireset
                        tireset.ContainerCargoRoomId = NewContainerCargoRoomId;

                        // Create log
                        bll.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, NewContainerCargoRoomId);
                    }
                    else
                    {
                        // Other tireset occupy cargoroom - move around

                        // Reset occupying tireset cargoroom
                        TireSetOccupying.ContainerCargoRoomId = null;

                        // Update tireset
                        tireset.ContainerCargoRoomId = NewContainerCargoRoomId;

                        // Create log
                        bll.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, NewContainerCargoRoomId);

                        // Give occupying tireset new cargoroom
                        TireSetOccupying.ContainerCargoRoomId = containercargoroomid;

                        // Create log for occupying tireset
                        bll.CreateTireSetLog(db, TireSetOccupying, DateTime.Now, TireSetOccupying.TireSetStatusId, TireSetOccupying.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, TireSetOccupying.ContainerCargoRoomId);
                    }
                }

                // Commit changes to database
                db.SubmitChanges();

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }

    }
}